package br.edu.ufcg.dsc.services;

import java.util.List;

import org.yaz4j.Connection;
import org.yaz4j.PrefixQuery;
import org.yaz4j.ResultSet;

import br.edu.ufcg.dsc.domain.Resource;
import br.edu.ufcg.dsc.domain.ResourceType;
import br.edu.ufcg.dsc.domain.marc.MARCResource;
import br.edu.ufcg.dsc.domain.marc.parser.MARCXMLParser;

public class Z3950Service {

	public static void fill(List<Resource> resources, String attribute, String query, int page) {
		Connection conn = new Connection("z3950.loc.gov", 7090);
		conn.setDatabaseName("Voyager");
		conn.setSyntax("XML");

		conn.Connect();
		
		String q = "@attr 1=" + attribute;
		q += " " + "\"" + query + "\"";
		
		PrefixQuery pqf = new PrefixQuery(q);
		ResultSet set = conn.Search(pqf);

		for (int i = (page - 1) * 5; i < Math.min(set.getSize(), page * 5); i++) {

			if (set.getRecord(i).render() == null)
				continue;

			resources.add(new Resource(new MARCXMLParser().parseResource(set
					.getRecord(i).render()), ResourceType.ALL));
		}

		conn.Dispose();		
	}

	public static MARCResource getResource(String attribute, String query,
			int position) {
		
		Connection conn = new Connection("z3950.loc.gov", 7090);
		conn.setDatabaseName("Voyager");
		conn.setSyntax("XML");

		conn.Connect();
		
		String q = "@attr 1=" + attribute;
		q += " " + "\"" + query + "\"";
		
		PrefixQuery pqf = new PrefixQuery(q);
		ResultSet set = conn.Search(pqf);

		MARCResource marc = new MARCXMLParser().parseResource(set
				.getRecord(position).render());
		
		conn.Dispose();	

		return marc;
	}

}
